<?php

namespace App\Admin\Middleware;

use App\Events\OperationLogEvent;
use Closure;

class OperationMiddleware
{
    private $except = [
        'admin.login',
    ];

    /**
     * 操作日志
     * @param          $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!in_array($request->route()->getName(), $this->except)) {

            try {
                $data = [
                    'admin_id'         => $request->user('admin')->id ?? 0,
                    'admin_name'       => $request->user('admin')->name ?? '',
                    'staff_id'         => $request->user('admin')->staff_id ?? 0,
                    'route_name'       => $request->route()->getName() ?? '',
                    'route_permission' => $request->route()->getActionDescription() ?? '',
                    'method'           => $request->method(),
                    'uri'              => $request->path(),
                    'url'              => $request->url(),
                    'full_url'         => $request->fullUrl(),
                    'ip'               => $request->getClientIp(),
                    'session_id'       => $request->getSession()->getId(),
                    'query'            => $request->except(['password', 'sn', 'token']),
                    'user_agent'       => $request->userAgent(),
                    'operated_at'      => now()->toDateTimeString(),
                ];
                event(new OperationLogEvent($data));
            } catch (\Exception $e) {
                info('Record operation log faild, error:' . $e->getMessage());
            }
        }

        return $next($request);
    }
}
